package com.learn.scrm;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.*;

@Data
@Configuration
@ConfigurationProperties(prefix = "schedule")
@Slf4j
public class ScheduleConfig {

    private static final long serialVersionUID = 1L;

    private String yqGateWay;

    private Map<String, ScheduleItem> scheduleItems;

    private Map<String, List<ScheduleItem>> roleScheduleCache = new HashMap<>();

    public void setScheduleItems(Map<String, ScheduleItem> scheduleItems) {
        this.scheduleItems = scheduleItems;
        roleScheduleCache.clear();
        if (Objects.nonNull(scheduleItems) && !scheduleItems.isEmpty()) {
            scheduleItems.forEach((k, v) -> {
                v.setCode(k);
                if (StrUtil.isNotEmpty(v.getAuth())){
                    String[] role = v.getAuth().split(",");
                    for (String r : role) {
                        List<ScheduleItem> list = roleScheduleCache.getOrDefault(r, new ArrayList<>());
                        list.add(v);
                        roleScheduleCache.put(r, list);
                    }
                }
            });
        }
        log.info("初始化角色应用列表:{}", JSONUtil.toJsonStr(roleScheduleCache));
    }

    public List<ScheduleItem> getScheduleByRole(String role) {
        return roleScheduleCache.get(role);
    }

    public String getScheduleApiByCode(String code) {
        ScheduleItem item = scheduleItems.get(code);
        if (Objects.nonNull(item)) {
            return item.getExecUrl();
        }
        return null;
    }

    @Data
    public static class ScheduleItem {
        //标识符
        private String code;
        //图标
        private String logoUrl;
        //跳转地址
        private String scheduleUrl;
        //接口地址
        private String execUrl;
        //名称
        private String name;
        //排序
        private Double sort;

        private String group;
        //角色
        private String auth;
        // 忽略此待办的品牌
        private String ignoreBrand;
    }
}
